package com.kcl.dfss;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.kcl.dfss.http.ServerConnection;

public class SelectModelActivity extends Activity {

	private LinearLayout select_model_back;
	private ArrayList<HashMap<String, String>> list;
	private ListView list_model;
	private ProgressBar progress_model;
	
	private String[] data;
	private String[] indexdata;
	
	private String braid,serid;
	
	ModelAdapter modelAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_select_model);
		
		select_model_back = (LinearLayout) findViewById(R.id.select_model_back);
		select_model_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		progress_model = (ProgressBar) findViewById(R.id.progress_model);
		
		SharedPreferences preferences = getSharedPreferences("shared_login", 0);
		final String userid = preferences.getString("userid", "");
		
		final Handler handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 1){
					sortIndex();
					list_model = (ListView) findViewById(R.id.list_model);
					modelAdapter = new ModelAdapter(SelectModelActivity.this);
					list_model.setAdapter(modelAdapter);
					progress_model.setVisibility(View.GONE);
					list_model.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view,
								int position, long id) {
							if(userid.equals("")){
								
								SharedPreferences camcfg = getSharedPreferences("camcfg", 0);
								camcfg.edit().putString("brandID", braid).commit();
								camcfg.edit().putString("seriesID", serid).commit();
								camcfg.edit().putString("modelID", indexdata[position].substring(indexdata[position].indexOf(",")+1)).commit();
								
								Intent intent = new Intent();
								/*intent.putExtra("braId", braid);
								intent.putExtra("serid", serid);
								intent.putExtra("modid", indexdata[position].substring(indexdata[position].indexOf(",")+1));*/
								intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
								intent.setClass(SelectModelActivity.this, MatchingCarActivity.class);
								startActivity(intent);	
								finish();
							}else{
								SharedPreferences addDevice = getSharedPreferences("adddevice", 0);
								boolean select = addDevice.getBoolean("select", false);
//								addDevice.edit().putBoolean("select", true).commit();
								if(select){
									SharedPreferences camcfg = getSharedPreferences("camcfg", 0);
									camcfg.edit().putString("brandID", braid).commit();
									camcfg.edit().putString("seriesID", serid).commit();
									camcfg.edit().putString("modelID", indexdata[position].substring(indexdata[position].indexOf(",")+1)).commit();
									
									Intent intent = new Intent();
									/*intent.putExtra("braId", braid);
									intent.putExtra("serid", serid);
									intent.putExtra("modid", indexdata[position].substring(indexdata[position].indexOf(",")+1));*/
									intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									intent.setClass(SelectModelActivity.this, MatchingCarActivity.class);
									startActivity(intent);	
									addDevice.edit().putBoolean("select", false).commit();
									finish();
								}else{
									final String modid = indexdata[position].substring(indexdata[position].indexOf(",")+1);
									new Thread(new Runnable() {
										@Override
										public void run() {
											
										}
									}).start();
									Intent intent = new Intent();
									intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
									intent.putExtra("carmodel", indexdata[position].substring(5,indexdata[position].indexOf(",")));
									intent.setClass(SelectModelActivity.this, DeviceSetActivity.class);
									startActivity(intent);
									finish();
								}
								
							}
						}
					});
				}
			}
			
		};
		
		Intent intent = getIntent();
		serid = intent.getStringExtra("serid");
		braid = intent.getStringExtra("braid");
		
		
		list = new ArrayList<HashMap<String,String>>();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String result = ServerConnection.GetModel(serid, userid);
				try {
					JSONObject jsonObject = new JSONObject(result);
					JSONArray jsonArray = jsonObject.getJSONArray("data");
					HashMap<String, String> map = null;
					data = new String[jsonArray.length()];
					for(int i=0;i<jsonArray.length();i++){
						
						JSONObject jo = (JSONObject) jsonArray.opt(i);
						data[i] = jo.getString("modname")+","+jo.getString("modid");
						
					}
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
		}).start();
		
	}
	
	//获取排序后的数据
	public void sortIndex(){
		
		TreeSet<String> set = new TreeSet<String>();
		for(String string:data){
			set.add(String.valueOf(string.substring(0, 5)));
		}
		indexdata = new String[data.length+set.size()];
		int i = 0;
		for(String string:set){
			indexdata[i] = string;
			i++;
		}
		System.arraycopy(data, 0, indexdata, set.size(), data.length);
		Arrays.sort(indexdata,String.CASE_INSENSITIVE_ORDER);
	}
	
	private class ModelAdapter extends BaseAdapter{

		Context context;
		
		public ModelAdapter(Context context) {
			this.context = context;
		}
		
		@Override
		public int getCount() {
			return indexdata.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return indexdata[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			String[] copyindex = new String[indexdata.length];
			for(int i=0;i<indexdata.length;i++){
				if(indexdata[i].length() == 5){
					copyindex[i] = indexdata[i];
				}else{
					copyindex[i] = indexdata[i].substring(5,indexdata[i].indexOf(","));					
				}
			}
			String item = copyindex[position];
			if(item.length() == 5){
				convertView = getLayoutInflater().inflate(R.layout.select_car_title, null);
				TextView text_letter = (TextView) convertView.findViewById(R.id.text_letter);
				text_letter.setText(item);
			}else{
				convertView = getLayoutInflater().inflate(R.layout.select_car_item, null);
				TextView text_carname = (TextView) convertView.findViewById(R.id.text_carname);
				text_carname.setText(item);
			}
			return convertView;
		}
		
	}

}
